package com.duolaibei.pay.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.duolaibei.pay.R;
import com.duolaibei.pay.adapter.PayAdapter;
import com.duolaibei.pay.base.BaseActivity;
import com.duolaibei.pay.base.MyApplication;
import com.duolaibei.pay.bean.PayOrder;
import com.duolaibei.pay.http.BaseCallback;
import com.duolaibei.pay.http.ParamsUtils;
import com.duolaibei.pay.http.Result;
import com.duolaibei.pay.http.api.ApiName;
import com.duolaibei.pay.utils.SharedPreferencesUtils;
import com.duolaibei.pay.utils.ToastUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by wangshuo on 2017/7/12.
 */

public class BrushDetailActivity extends BaseActivity implements BaseCallback<Result<Map<String, Object>>> {
    @Bind(R.id.back)
    RelativeLayout back;
    @Bind(R.id.statistical_tt)
    TextView statisticalTt;
    @Bind(R.id.statistical_time)
    TextView statisticalTime;
    @Bind(R.id.top_rt)
    RelativeLayout topRt;
    @Bind(R.id.total_tt)
    TextView totalTt;
    @Bind(R.id.count_tt)
    TextView countTt;
    @Bind(R.id.middle_rt)
    RelativeLayout middleRt;
    @Bind(R.id.print_bt)
    Button printBt;
    @Bind(R.id.below_rt)
    RelativeLayout belowRt;
    @Bind(R.id.title_ll)
    LinearLayout titleLl;
    @Bind(R.id.detail_list)
    ListView detailList;

    private int pageIndex = 1;
    private int pageNum = 10;
    private static final String PAY_TYPE = "22";// 刷卡类型
    private Calendar c = Calendar.getInstance();
    private Intent intent = null;
    private PayAdapter adapter;
    List<PayOrder> orders;
    String sumMoney;
    String count;
    public static final int INDEX_TYPE = 200;

    @Override
    public int getContentViewResId() {
        return R.layout.activity_detail;
    }

    @Override
    public void intiViews() {
        adapter = new PayAdapter(this);
        detailList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                intent = new Intent(BrushDetailActivity.this, DealDetailsActivity.class);
                PayOrder po = (PayOrder) adapter.getItem(i);
                intent.putExtra("order", po);
                intent.putExtra("index", INDEX_TYPE);

                startActivity(intent);
            }
        });
        detailList.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
                if (null == orders || absListView.getCount() < pageNum) {
                    return;
                }

                // 当不滚动时
                if (i == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (absListView.getLastVisiblePosition() == absListView.getCount() - 1) {
                        //加载更多功能的代码
                        getBrushAllOrder();
                    }
                }

            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });
        detailList.setAdapter(adapter);
        printBt.setOnClickListener(this);
        TextView tv = (TextView) findViewById(R.id.statistical_time);
        String month = ((c.get(Calendar.MONTH) + 1) < 10 ? "0" + (c.get(Calendar.MONTH) + 1) : (c.get(Calendar.MONTH) + 1)) + "";
        String day = c.get(Calendar.DATE) < 10 ? "0" + c.get(Calendar.DATE) : c.get(Calendar.DATE) + "";
        tv.setText(c.get(Calendar.YEAR) + "-" + month + "-" + day);
        getBrushAllOrder();
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        int id = view.getId();
        if (id == R.id.print_bt) {
            //结算
            Intent intent1 = initIntent();
            intent1.putExtra("transName", "4");//结算
            startActivityForResult(intent1, 0);
        }
    }

    //抽取各个交易类型公共的字段
    private Intent initIntent() {
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.shengpay.smartpos.shengpaysdk", "com.shengpay.smartpos.shengpaysdk.activity.MainActivity"));
        intent.putExtra("appId", getPackageName());
        return intent;
    }

    private void getBrushAllOrder() {
        MyApplication.getSerivceApi().getBrushAllOrder(SharedPreferencesUtils.getAppid(),
                ApiName.GET_ALL_ORDER, ParamsUtils.getAllOrder("", "", pageIndex + "", pageNum + "", "1", PAY_TYPE), SharedPreferencesUtils.getTerminalNumber(), SharedPreferencesUtils.getWorkMenId(),
                "", "", pageIndex + "", pageNum + "", "1", PAY_TYPE).enqueue(this);
    }

    @Override
    public String setTitle() {
        return "刷卡统计";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void onResponse(Call<Result<Map<String, Object>>> call, Response<Result<Map<String, Object>>> response) {
        if (response.code() == 200) {
            if (response.body().getStatus().equals("1")) {
                List<Map<String, String>> payOrders = (List<Map<String, String>>) response.body().getResult().get("list");
                if (null == payOrders || payOrders.size() == 0) {
                    ToastUtils.showToast(BrushDetailActivity.this, "没有数据", 3000);
                    return;
                }
                orders = mapToPayorder(payOrders);
                adapter.setData(orders);

                sumMoney = response.body().getResult().get("today_count_amount").toString();
                Log.v("------", "======" + sumMoney);
                count = response.body().getResult().get("today_count_order").toString();
                totalTt.setText(getString(R.string.today_deal_sum, sumMoney));
                countTt.setText(getString(R.string.today_deal_count, ((int) Double.parseDouble(count)) + ""));
                pageIndex++;
            }
        }
    }

    @Override
    public void onFailure(Call<Result<Map<String, Object>>> call, Throwable t) {
        Log.v("onFailure", "error message" + t.getMessage());
    }

    private List<PayOrder> mapToPayorder(List<Map<String, String>> data) {
        List<PayOrder> list = new ArrayList<>();
        int length = data.size();
        PayOrder po = null;
        for (int i = 0; i < length; i++) {
            po = new PayOrder();
            po.setOut_trade_no(data.get(i).get("out_trade_no"));
            po.setBody(data.get(i).get("body"));
            po.setUid(data.get(i).get("uid"));
            po.setTrade_no(data.get(i).get("trade_no"));
            po.setService(data.get(i).get("service"));
            po.setProduct_id(data.get(i).get("product_id"));
            po.setPay_type(data.get(i).get("pay_type"));
            po.setTotal_amount(data.get(i).get("total_amount"));
            po.setDiscountable_amount(data.get(i).get("discountable_amount"));
            po.setPay_amount(data.get(i).get("pay_amount"));
            po.setUid(data.get(i).get("pay_uid"));
            po.setShop_id(data.get(i).get("shop_id"));
            po.setTerminal_id(data.get(i).get("terminal_id"));
            po.setAgent_uid(data.get(i).get("agent_uid"));
            po.setWorkmen_id(data.get(i).get("workmen_uid"));
            po.setStatus(data.get(i).get("status"));
            po.setPaytime(data.get(i).get("paytime"));
            po.setAddtime(data.get(i).get("addtime"));
            po.setUptime(data.get(i).get("uptime"));
            po.setPay_name(data.get(i).get("pay_name"));
            list.add(po);
        }
        return list;
    }
}
